package admin.controllers;

import helpers.CookieHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import search.ArticleSearchEngine;
import systems.Recently;

import entities.Application;
import entities.Article;

import admin.models.ApplicationModel;
import admin.models.ArticleModel;

public class ArticleDeleteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setContentType("text/html");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (params == null || params.isEmpty()) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		String[] pr = params.split("/");
		
		if (pr.length < 2) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		String articleId = pr[0];
		String id = pr[1];
		
		ApplicationModel appModel = ApplicationModel.getInstance();
		Application app = appModel.get(id);
		
		if (app == null) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		try {
			ArticleModel articleModel = ArticleModel.getInstance();
			Article article = articleModel.getArticle(app.getId(), articleId);
			articleModel.delete(app.getId(), article);
			
			//Remove recently cache
			Recently.remove(id, article);
			
			CookieHelper.setCookie(response, "success", "Delete success article " + articleId);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		response.sendRedirect("/admin/article/list/" + id);
	}
}
